﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace SingleBlog.Web.Areas.Admin.Controllers
{
    using Core.Data;
    using Core.SettingModels;
    using Core.Services;
    using Framework;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.Extensions.Caching.Memory;
    using SingleBlog.Web.Areas.Admin.Models;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;

    [Area("admin")]
    [Authorize(Roles = SingleBlogRole.ADMINISTRATOR)]
    public class SettingController : Controller
    {
        private readonly SettingService _settingService;
        private readonly UserManager<SingleBlogUser> _userManager;
        private readonly NavigationService _navigationService;
        private readonly IMemoryCache _cache;
        private readonly IMessageSender _messageSender;
        private readonly ILogger _logger;
        public SettingController(
            SettingService settingService,
            UserManager<SingleBlogUser> userManager,
            NavigationService navigationService,
            IMemoryCache cache,
            IMessageSender messageSender,
            ILoggerFactory loggerFactory
            )
        {
            _settingService = settingService;
            _userManager = userManager;
            _navigationService = navigationService;
            _cache = cache;
            _messageSender = messageSender;
            _logger = loggerFactory.CreateLogger<SettingController>();
        }

        #region 站点信息
        public IActionResult Site()
        {
            var model = _settingService.GetGeneralSetting();
            return View(model);
        }

        [HttpPost]
        public IActionResult Site(GeneralSettingModel model)
        {
            try
            {
                _settingService.SaveSetting(model);

                TempData["Submit"] = true;
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("error", ex.Message);
            }
            return View(model);
        }
        #endregion

        #region 修改密码
        public IActionResult ChangePwd() => View();

        [HttpPost]
        public async Task<IActionResult> ChangePwd(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("error", "表单校验不正确");
                return View(model);
            }
            var user = await _userManager.FindByIdAsync(User.Identity.UserId().ToString());
            if (user == null)
            {
                ModelState.AddModelError("error", "当前用户不存在或已被删除");
                return View(model);
            }

            var result = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword);
            if (!result.Succeeded)
            {
                ModelState.AddModelError("error", result.Errors.Select(m =>$"{m.Code}：{m.Description}").Join("；"));
            }
            else
            {
                TempData["Success"] = true;
            }
            return View(model);
        }
        #endregion

        #region SMTP 
        public IActionResult Smtp()
        {
            try
            {
                var setting = _settingService.GetSmtpSetting();
                return View(setting);
            }
            catch
            {
                return View(new SmtpSettingModel { Port = 25 });
            }
        }
        [HttpPost]
        public async Task<IActionResult> Smtp(SmtpSettingModel model)
        {
            try
            {
                _settingService.SaveSetting(model);

                TempData["Submit"] = true;
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("error", ex.Message);
            }
            return View(model);
        }

        public IActionResult SmtpTest()
        {
            try
            {
                var model = _settingService.GetSmtpSetting();
                if (!model.IsValid())
                {
                    ModelState.AddModelError("error", model.GetErrors().Join("；"));
                    return View();
                }
            }
            catch(Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                ModelState.AddModelError("error", "SMTP 配置不正确");
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> SmtpTest(IFormCollection collection)
        {
            var receiver = (string)collection["Receiver"];
            if (!receiver.IsMatchEmail())
            {
                ModelState.AddModelError("error", "邮箱输入不正确");
                return View(nameof(SmtpTest));
            }

            var model= _settingService.GetSmtpSetting();
            if (!model.IsValid())
            {
                ModelState.AddModelError("error", model.GetErrors().Join("；"));
                return View(nameof(SmtpTest));
            }

            try
            {
                await _messageSender.SendAsync(new MailMessage("SMTP 测试邮件", @"Hello 这是一封测试邮件，不需要回复。", receiver));

                TempData["Submit"] = true;
                return View(nameof(SmtpTest));
            }catch(Exception ex)
            {
                ModelState.AddModelError("error", $"邮件发送失败，错误信息：{ex.Message}");
                return View(nameof(SmtpTest));
            }
        }
        #endregion

        #region UserInfo
        public async Task<IActionResult> UserInfo()
        {
            var user = await _userManager.FindByIdAsync(User.Identity.UserId().ToString());
            return View(new UserInfoViewModel { Email=user.Email,Mobile=user.PhoneNumber });
        }
        [HttpPost]
        public async Task<IActionResult> UserInfo(UserInfoViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("error", "表单校验不正确");
                return View(model);
            }

            try
            {
                var user = await _userManager.FindByIdAsync(User.Identity.UserId().ToString());
                await _userManager.SetEmailAsync(user, model.Email);

                if (!model.Mobile.IsNullOrEmpty())
                {
                    await _userManager.SetPhoneNumberAsync(user, model.Mobile);
                }

                TempData["Submit"] = true;
            }
            catch(Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                ModelState.AddModelError("error", $"提交失败，错误信息：{ex.Message}");
            }
            return View(model);
        }
        #endregion

        #region 导航
        public async Task<IActionResult> NavigationList()
        {
            var list = await _navigationService.GetNavigationsAsync(false);
            return View(list);
        }
        [HttpGet]
        public async Task<IActionResult> NavigationEdit(int? id)
        {          

            if (id.HasValue)
            {
                var entity = await _navigationService.GetNavigationAsync(id.Value);
                return View(entity);
            }
            return View(new Navigation());
        }
        [HttpPost]
        public async Task<IActionResult> NavigationEdit(Navigation navigation)
        {
            if (navigation == null)
            {
                throw new ArgumentNullException(nameof(navigation));
            }
            await _navigationService.SaveNavigationAsync(navigation);
            return RedirectToAction(nameof(NavigationList));
        }
        [HttpPost]
        public async Task<IActionResult> NavigationDelete(int id)
        {
            await _navigationService.DeleteNavigationAsync(id);
            return Ok();
        }
        #endregion
    }
}